package com.gemme.gemme.home;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.gemme.gemme.BaseActivity;
import com.gemme.gemme.R;
import com.gemme.gemme.login.Constant;
import com.gemme.gemme.manager.DataManager;
import com.gemme.gemme.view.DefineLoadMoreView;
import com.gemme.gemme.view.GeAddressButton;
import com.gemme.gemme.view.StaggeredDividerItemDecoration;
import com.gemme.gemme.view.TopIvBottomTextView;
import com.gemme.gemme.view.Topview;
import com.gemme.gemme.wode.AddAddressActivity;
import com.gemme.gemme.wode.AddressNewActivity;
import com.gemme.gemme.wode.DefineActivity;
import com.gemme.gemme.wode.MainAdapter;
import com.gemme.gemme.wode.ProductNewActivity;
import com.google.android.material.tabs.TabLayout;
import com.jaeger.library.StatusBarUtil;
import com.yanzhenjie.recyclerview.OnItemClickListener;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;
import com.yanzhenjie.recyclerview.widget.DefaultItemDecoration;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

/**
 * @Author: yangcheng
 * @CreateDate: 2020/6/30 11:41
 */
public class ProductListActivity extends BaseActivity {
    String keyWork;
    String brandId;
    String categoryName;
    String twoCategoryId;
    String price;
    String remode;
    String hotSale;
    String sortOrder;
    String discount;
    String productEffectId ;
    int current = 1 ;
    int size = 100;
    ProductListAdapter mAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_list);
        StatusBarUtil.setTransparent(this);
        initTop();
        initTabLayout();
        initView();
        getIntentData();
        initData();

    }

    public void getIntentData(){
        Intent intent = getIntent();
         keyWork = intent.getStringExtra("keyWork");
         brandId = intent.getStringExtra("BrandId");
         categoryName = intent.getStringExtra("categoryName");
        System.out.println("");
    }

    ProductListBean productListBean;

    private void initData() {
        String url = DataManager.BaseUrl_panghu + "mall/esProduct/searchRelated?";

        if(!TextUtils.isEmpty(keyWork)){
            url = url + "keyWork=" + keyWork;
        }else if(!TextUtils.isEmpty(brandId)){
            url = url + "brandId=" + brandId;
        }else if(!TextUtils.isEmpty(categoryName)){
            url = url + "categoryName=" + categoryName;
        }

        if(!TextUtils.isEmpty(twoCategoryId)){
            url = url + "&twoCategoryId=" + twoCategoryId;
        }
        if(!TextUtils.isEmpty(price))
        url = url + "&price=" + price;//1-1000  1-   -1
        //remode = remode ： 推荐
        if(!TextUtils.isEmpty(remode))
            url = url + "&remode=" + remode;
        //hotSale = soldNum-desc ；热销
        if(!TextUtils.isEmpty(hotSale))
            url = url + "&hotSale=" + hotSale;

        //sortOrder = price-desc :价格排序
        if(!TextUtils.isEmpty(sortOrder))
            url = url + "&sortOrder=" + sortOrder;
        //discount = discount :查看折扣
        if(!TextUtils.isEmpty(discount))
            url = url + "&discount=" + discount;

        if(!TextUtils.isEmpty(productEffectId))
        url = url + "&productEffectId=" + productEffectId;   // 美白 : 1278521450449358849 保湿 : 1278521486050611201
        if(current!=0)
            url = url + "&current=" + current;
        if(size!=0)
            url = url + "&size=" + size;


        HashMap<String, String> headMap = new HashMap<>();
        //todo 去除token
//        headMap.put(DataManager.AuthorizationKey,DataManager.getToken(mContext));
        DataManager.toServer2(mContext, url, DataManager.GET_TYPE, "", headMap, new DataManager.GeResponse() {
            @Override
            public void onResponse(String response) {
                try {

                    productListBean = JSON.parseObject(response, ProductListBean.class);
                    List<ProductListBean.DataBean.ProductEsVoListBean> productEsVoList = productListBean.getData().getEsProductInfoList();
                    System.out.println("");
                    if(productEsVoList != null){
//                        mAdapter.notifyDataSetChanged(productEsVoList);

                        mRefreshLayout.setRefreshing(false);

                        initMiddle();
                        // 第一次加载数据：一定要掉用这个方法。
                        // 第一个参数：表示此次数据是否为空，假如你请求到的list为空(== null || list.size == 0)，那么这里就要true。
                        // 第二个参数：表示是否还有更多数据，根据服务器返回给你的page等信息判断是否还有更多，这样可以提供性能，如果不能判断则传true。
                        //暂时去除加载更多
//                        mRecyclerView.loadMoreFinish(false, true);
                        mRecyclerView.loadMoreFinish(false, false);

                        if(mAdapter == null){
                            mAdapter = new ProductListAdapter(productEsVoList);
                            mRecyclerView.setAdapter(mAdapter);
                        }else{
                            mAdapter.setData(productEsVoList);
                            mAdapter.notifyDataSetChanged();
                        }



                    }

                }catch (Exception e){

                }
                System.out.println("");
            }
        });
    }

    private void initMiddle() {
        try {
//            ll_middle.removeAllViews();
            if(ll_middle.getChildCount() > 0)
                return;
            List<ProductListBean.DataBean.CategoryVoListBean> categoryVoList = productListBean.getData().getCategoryVoList();
            System.out.println("");
            for (int i = 0; i < categoryVoList.size(); i++) {
                ProductListBean.DataBean.CategoryVoListBean categoryVoListBean = categoryVoList.get(i);
                TopIvBottomTextView topIvBottomTextView = new TopIvBottomTextView(mContext);
                topIvBottomTextView.setData(categoryVoListBean);
                ll_middle.addView(topIvBottomTextView);

                topIvBottomTextView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        twoCategoryId = categoryVoListBean.getCategoryId() + "";
                        initData();
                    }
                });
            }
        }catch (Exception e){

        }
    }

    private SwipeRefreshLayout mRefreshLayout;
    private SwipeRecyclerView mRecyclerView;
    private List<String> mDataList;
    LinearLayout ll_middle;
    private void initView() {
        mRefreshLayout = findViewById(R.id.refresh_layout);


        mRecyclerView = findViewById(R.id.recycler_view);
//        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        StaggeredGridLayoutManager layoutManager = new
                StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.addItemDecoration(new StaggeredDividerItemDecoration
                (mContext, (int) getResources().getDimension(R.dimen.dp_11)));

//        mRecyclerView.addItemDecoration(new DefaultItemDecoration(ContextCompat.getColor(this, R.color.divider_color)));
        mRecyclerView.setOnItemClickListener(mItemClickListener);

        // 自定义的核心就是DefineLoadMoreView类。
        DefineLoadMoreView loadMoreView = new DefineLoadMoreView(this);
        mRecyclerView.addFooterView(loadMoreView); // 添加为Footer。
        mRecyclerView.setLoadMoreView(loadMoreView); // 设置LoadMoreView更新监听。
        mRefreshLayout.setOnRefreshListener(mRefreshListener); // 刷新监听。
        mRecyclerView.setLoadMoreListener(mLoadMoreListener); // 加载更多的监听。


        ll_middle = findViewById(R.id.ll_middle);
//        mAdapter = new ProductListAdapter();
//        mRecyclerView.setAdapter(mAdapter);

        // 请求服务器加载数据。
//        loadData();

        findViewById(R.id.meibai).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                productEffectId = "1278521450449358849";
                mRefreshLayout.setRefreshing(true);
                initData();
            }
        });
        findViewById(R.id.baoshi).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                productEffectId = "1278521486050611201";
                mRefreshLayout.setRefreshing(true);
                initData();
            }
        });
    }



    public  class ProductListAdapter extends RecyclerView.Adapter<ProductListAdapter.ViewHolder>{
        private List<ProductListBean.DataBean.ProductEsVoListBean> mDataList;

        public ProductListAdapter(List<ProductListBean.DataBean.ProductEsVoListBean> dataList){
            this.mDataList = dataList;
        }

        public void  setData(List<ProductListBean.DataBean.ProductEsVoListBean> dataList){
            this.mDataList = dataList;
        }
/*
        public void notifyDataSetChanged(List<ProductListBean.DataBean.ProductEsVoListBean> dataList) {
            this.mDataList = dataList;
            super.notifyDataSetChanged();
        }
*/
        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View inflate = LayoutInflater.from(parent.getContext()).
                    inflate(R.layout.product_list_item2, null);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            inflate.setLayoutParams(layoutParams);
            return new ProductListAdapter.ViewHolder(inflate);
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            try{
                ProductListBean.DataBean.ProductEsVoListBean bean = mDataList.get(position);
                holder.name.setText(bean.getBrandName());
                holder.des.setText(bean.getProductName());
                holder.price.setText(bean.getPrice() + "");
//                holder.picture
                String productImg = bean.getAbbreviationPic();
                if(TextUtils.isEmpty(productImg)){
                    holder.picture.setImageResource(0);
                }
                if( productImg.contains(",")){
                    productImg = productImg.substring(0,productImg.indexOf(","));
                }
                Glide.with(holder.picture.getContext()).load(productImg).into(holder.picture);


                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //todo 进入产品详情有问题
                        Intent intent = new Intent(mContext, ProductNewActivity.class);
                        intent.putExtra("id",bean.getProductId() + 0L);
                        intent.putExtra("brandId",bean.getBrandId() + 0L);
                        startActivity(intent);
                    }
                });
            }catch (Exception e){

            }
        }

        @Override
        public int getItemCount() {
            return mDataList.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            TextView name;
            TextView des;
            TextView price;
            ImageView picture;
            public ViewHolder(@NonNull View itemView) {
                super(itemView);

                name = itemView.findViewById(R.id.name);
                des = itemView.findViewById(R.id.des);
                price = itemView.findViewById(R.id.price);
                picture = itemView.findViewById(R.id.picture);
            }
        }
    }
/* todo yc
    *//**
     * 第一次加载数据。
     *//*
    private void loadData() {
        mDataList = createDataList(0);
        mAdapter.notifyDataSetChanged(mDataList);

        mRefreshLayout.setRefreshing(false);

        // 第一次加载数据：一定要掉用这个方法。
        // 第一个参数：表示此次数据是否为空，假如你请求到的list为空(== null || list.size == 0)，那么这里就要true。
        // 第二个参数：表示是否还有更多数据，根据服务器返回给你的page等信息判断是否还有更多，这样可以提供性能，如果不能判断则传true。
        mRecyclerView.loadMoreFinish(false, true);
    }

    protected List<String> createDataList(int start) {
        List<String> strings = new ArrayList<>();
        for (int i = start; i < start + 20; i++) {
            strings.add("第" + i + "个Item");
        }
        return strings;
    }*/


    /**
     * 加载更多。
     */
    private SwipeRecyclerView.LoadMoreListener mLoadMoreListener = new SwipeRecyclerView.LoadMoreListener() {
        @Override
        public void onLoadMore() {
            //todo yc
           /* mRecyclerView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    List<String> strings = createDataList(mAdapter.getItemCount());
                    mDataList.addAll(strings);
                    // notifyItemRangeInserted()或者notifyDataSetChanged().
                    mAdapter.notifyItemRangeInserted(mDataList.size() - strings.size(), strings.size());

                    // 数据完更多数据，一定要掉用这个方法。
                    // 第一个参数：表示此次数据是否为空。
                    // 第二个参数：表示是否还有更多数据。
                    mRecyclerView.loadMoreFinish(false, true);

                    // 如果加载失败调用下面的方法，传入errorCode和errorMessage。
                    // errorCode随便传，你自定义LoadMoreView时可以根据errorCode判断错误类型。
                    // errorMessage是会显示到loadMoreView上的，用户可以看到。
                    // mRecyclerView.loadMoreError(0, "请求网络失败");
                }
            }, 1000);*/
        }
    };

    /**
     * 刷新。
     */
    private SwipeRefreshLayout.OnRefreshListener mRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            mRecyclerView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    //todo yc
                    current = 1;
                    initData();
                }
            }, 1000); // 延时模拟请求服务器。
        }
    };

    /**
     * Item点击监听。
     */
    private OnItemClickListener mItemClickListener = new OnItemClickListener() {
        @Override
        public void onItemClick(View itemView, int position) {
            Toast.makeText(mContext, "第" + position + "个", Toast.LENGTH_SHORT).show();
        }
    };


    TabLayout mTabLayout;
    ArrayList<String> tab_list = new ArrayList<>();

    private void initTabLayout() {
        mTabLayout = findViewById(R.id.tablayout);
        tab_list.add("推荐");
        tab_list.add("热销");
        tab_list.add("价格");
        tab_list.add("折扣");
     /*   tab_list.add("样方");
        tab_list.add("植物");*/

        for (int i = 0; i < tab_list.size(); i++) {
            mTabLayout.addTab(mTabLayout.newTab().setText(tab_list.get(i) + ""));
        }

        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
//sort;  //price-asc  price-desc  lockCnt-asc     lockCnt-desc
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                System.out.println(" tab : onTabSelected");


                String tabText = tab.getText() + "";
                switch (tabText){
                    case "推荐":
                        remode = "remode";
                        hotSale = null;
                        sortOrder = null;
                        discount = null;
                        break;

                    case "热销":
                        remode = null;
                        hotSale = "soldNum-desc";
                        sortOrder = null;
                        discount = null;
                        break;

                    case "价格":
                        remode = null;
                        hotSale = null;
                        sortOrder = "price-desc";
                        discount = null;
                        break;

                    case "折扣":
                        remode = null;
                        hotSale = null;
                        sortOrder = null;
                        discount = "discount";
                        break;
                }
                twoCategoryId = null;  //选中tab二级分类设置为空
                mRefreshLayout.setRefreshing(true);
                initData();

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                System.out.println("tab : onTabUnselected");
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                System.out.println("tab : onTabReselected");
                if("价格".equals(tab.getText() + "")){
                    if("price-asc".equals(sortOrder)){
                        sortOrder = "price-desc";
                    }else{
                        sortOrder = "price-asc";
                    }
                   /* mRecyclerView.refreshDrawableState();*/
//                    initData();

                }else{
                    sortOrder = "";
                }


                mRefreshLayout.setRefreshing(true);
                initData();
            }
        });
    }




    private void initTop() {
//        StatusBarUtil.setColor(this,getResources().getColor(R.color.white_color) );
        StatusBarUtil.setTransparent(this);
//        StatusBarUtil.setTranslucent(this,250);
        Topview topview = findViewById(R.id.topview);
        topview.setContentText("护肤");


    }
}
